package com.wyc.serviceDriverUser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wyc.internalCommon.response.TerminalResponse;
import com.wyc.internalCommon.response.TrackResponse;
import com.wyc.internalCommon.result.ApiResult;
import com.wyc.internalCommon.util.PageUtils;
import com.wyc.internalCommon.util.Query;
import com.wyc.serviceDriverUser.dto.Car;
import com.wyc.serviceDriverUser.feign.ServiceMapFeignClient;
import com.wyc.serviceDriverUser.mapper.CarMapper;
import com.wyc.serviceDriverUser.service.CarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 司机车辆信息 服务实现类
 * </p>
 *
 * @author li
 * @since 2023-03-26
 */
@Service
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements CarService {

    @Autowired
    private CarMapper carMapper;

    @Autowired
    private ServiceMapFeignClient serviceMapFeignClient;

    /**
     * 插入或修改车辆信息
     * @param car
     * @return
     */
    @Transactional
    @Override
    public int insertOrUpdate(Car car) {
        int i = 0;
        if (null == car.getId()){
            i = carMapper.insert(car);
            // 添加终端id  tid
            ApiResult<TerminalResponse> result = serviceMapFeignClient.addTerminal(car.getVehicleNo(),String.valueOf(car.getId()));
            TerminalResponse data = result.getData();
            String tid = data.getTid();
            // 添加轨迹id
            ApiResult<TrackResponse> trackResult = serviceMapFeignClient.addTrack(tid);
            TrackResponse trackData = trackResult.getData();
            String trid = trackData.getTrid();
            String trname = StringUtils.hasLength(trackData.getTrname()) ? trackData.getTrname() : "";

            car.setTid(tid);
            car.setTrid(trid);
            car.setTrname(trname);
            carMapper.updateById(car);
        }else {
            i = carMapper.updateById(car);
        }
        return i;
    }

    /**
     * 列表
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String carId = (String) params.get("carId");
        QueryWrapper<Car> queryWrapper = new QueryWrapper<>();
        if (null != carId){
            queryWrapper.eq("id",carId);
        }

        IPage<Car> page = this.page(
                new Query<Car>().getPage(params,null,false),
                queryWrapper
        );


        return new PageUtils(page);
    }
}
